<template>
  <div id="dynamic-sort" class="dynamic-sort-echarts"></div>
</template>
<script>
import * as echarts from 'echarts/core'
import { GridComponent, LegendComponent } from 'echarts/components'
import { BarChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([GridComponent, LegendComponent, BarChart, CanvasRenderer])

export default {
  name: 'dynamicSort',
  data() {
    return {
      myECharts: null,
      echartsData: []
    }
  },
  created() {
    this.initData()
  },
  mounted() {
    this.initECharts()
    window.addEventListener('resize', this.resizeECharts)
    const timeout = setTimeout(() => {
      this.run()
    }, 0)
    const interval = setInterval(() => {
      this.run()
    }, 3000)
    this.$off('hook:destroyed', () => {
      clearTimeout(timeout)
      clearInterval(interval)
    })
  },
  destroyed() {
    window.removeEventListener('resize', this.resizeECharts)
  },
  methods: {
    initData() {
      for (let i = 0; i < 5; ++i) {
        this.echartsData.push(Math.round(Math.random() * 200))
      }
    },
    initECharts() {
      if (this.myECharts) {
        this.myECharts.dispose()
      }
      const echartsDom = document.getElementById('dynamic-sort')
      this.myECharts = echarts.init(echartsDom)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '1%',
          bottom: '4%',
          containLabel: true
        },
        xAxis: {
          max: 'dataMax'
        },
        yAxis: {
          type: 'category',
          data: ['A', 'B', 'C', 'D', 'E'],
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
          max: 2
        },
        series: [
          {
            realtimeSort: true,
            name: '动态图表',
            type: 'bar',
            data: this.echartsData,
            label: {
              show: true,
              position: 'right',
              valueAnimation: true
            }
          }
        ],
        legend: {
          show: true
        },
        animationDuration: 0,
        animationDurationUpdate: 3000,
        animationEasing: 'linear',
        animationEasingUpdate: 'linear'
      }
      option && this.myECharts.setOption(option)
    },
    run() {
      for (var i = 0; i < this.echartsData.length; ++i) {
        if (Math.random() > 0.9) {
          this.echartsData[i] += Math.round(Math.random() * 2000)
        } else {
          this.echartsData[i] += Math.round(Math.random() * 200)
        }
      }
      this.myECharts.setOption({
        series: [
          {
            type: 'bar',
            data: this.echartsData
          }
        ]
      })
    },
    resizeECharts() {
      if (this.myECharts) {
        this.myECharts.resize()
      }
    }
  }
}
</script>
<style lang="scss">
.dynamic-sort-echarts {
  width: 100%;
  min-height: 368px;
}
</style>
